﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySql.Data.MySqlClient;
using Gollie.Mail;

namespace Gollie.Ajax
{
	public class RegisterVendor : AjaxResult
	{
		public RegisterVendor() : base(null) { }

		public RegisterVendor(AjaxArg arg)
			: base(arg)
		{

		}

		protected override void Init(AjaxArg ajaxArg)
		{
			RegisterVendorArg arg = (RegisterVendorArg)ajaxArg;

			logger.Info("Consumer registration attempt...");

			try
			{
				string kvk = arg.token.Trim();
				string name = arg.companyname;
				string address = arg.address.Trim();
				string billingaccount = arg.billingaccount.Trim();
				string billingaddress = arg.billingaddress.Trim();
				string billingcity = arg.billingcity.Trim();
				string billingcountry = arg.billingcountry.Trim();
				string billingemail = arg.billingemail.Trim();
				string billingname = arg.billingname.Trim();
				string billingzipcode = arg.billingzipcode.Trim();
				string city = arg.city.Trim();
				string country = arg.country.Trim();
				string email = arg.email.Trim();
				string infix = arg.infix.Trim();
				string initials = arg.initials.Trim();
				string lastname = arg.lastname.Trim();
				string mobile = arg.mobile.Trim().Replace("-", "").Replace(" ", "");
				string website = arg.website.Trim();
				string zipcode = arg.zipcode.Trim();
				string sex = arg.sex;
				string logodata = arg.logodata;
				string logomimetype = arg.logomimetype;

				VendorInfo.ValidateName(name);
				VendorInfo.ValidateName(billingname);
				VendorInfo.ValidateAddress(address);
				VendorInfo.ValidateAddress(billingaddress);
				initials = UserInfo.ValidateInitials(initials);
				UserInfo.ValidateEmail(email);
				UserInfo.ValidateEmail(billingemail);
				mobile = UserInfo.ValidateTelePhone(mobile, false);
				billingzipcode = VendorInfo.ValidateZipcode(billingzipcode);
				zipcode = VendorInfo.ValidateZipcode(zipcode);
				billingaccount = VendorInfo.ValidateIBAN(billingaccount);
				website = VendorInfo.ValidateURL(website);

				string adminPassword = Hash.GetRandomPassword();
				string hashed = Hash.GetHash(adminPassword);
				uint newId;

				string adminUser = Database.Queries.RegisterVendor(
					name,
					address,
					zipcode,
					city,
					country,
					website,
					kvk,
					initials,
					infix,
					lastname,
					sex == "1",
					email,
					mobile,
					billingname,
					billingcountry,
					billingaccount,
					billingaddress,
					billingzipcode,
					billingcity,
					billingemail,
					hashed,
					out newId
					);

				logger.Info("Vendor registered {0}, admin: {1}", name, adminUser);

				this.SendMail(name, adminUser);

				if (logodata.Length > 14)
				{
					string fileExt = "";
					switch (logomimetype)
					{
						case "image/gif": fileExt = ".gif"; break;
						case "image/png": fileExt = ".png"; break;
						case "image/jpeg":
						case "image/pjpeg": fileExt = ".jpg"; break;
					}

					if (fileExt == "")
						throw new Exception("Het bestandsformaat van het logo kon niet bepaald worden. De registratie is wel voltooid, maar zonder uw bedrijfslogo");

					int index = logodata.IndexOf(";base64,", 14);
					if (index < 14)
						throw new Exception("Er is iets fout gegaan tijdens het uploaden van het logo. De registratie is wel voltooid, maar zonder uw bedrijfslogo");

					byte[] logoData = Convert.FromBase64String(logodata.Substring(index + 8));

					string logoPath = System.IO.Path.Combine(ConfigAppSettings.GetValue("VendorLogoFolder"), newId.ToString("00000000")) + fileExt;

					System.IO.File.WriteAllBytes(logoPath, logoData);
				}

			}
			catch (MySqlException mySqlEx)
			{
				this.ErrorCode = mySqlEx.Number;
				if (mySqlEx.Number == 1062)
					this.ErrorMessage = "Dit KvK nummer is al bekend bij Gollie.";
				else
					this.ErrorMessage = MySqlErrorCodes.GetInstance().GetMessage(mySqlEx);

				logger.Error("Vendor registration failed: {0}", this.ErrorMessage);
			}
			catch (Exception e)
			{
				if (this.ErrorCode == 0)
					this.ErrorCode = 99;

				this.ErrorMessage = e.Message;
				logger.Error("Vendor registration failed: {0}", this.ErrorMessage);
			}
		}

		private void SendMail(string businessName, string adminUser)
		{
			UserInfo admin = UserInfo.GetUserInfo(adminUser, false);

			MailClient.Queue(new EMail
			{
				Name = "vendorregistered",
				Recipients = admin.Email,
				Args = new Dictionary<string, string>()
				{
											{ "{businessname}", businessName },
											{ "{aanhef}", admin.MailAanhef },
											{ "{adminusername}", adminUser }
										    
				}
			});
		}

	}
}